<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,

      }"
      :table-props="{
        selection: false,
        delBtn: false,
        viewBtn: true,
        editBtn: false,
        menuSlot: true,
        menuWidth: 300,
        viewPermi: ['system:user:query'],
        editPermi: ['system:user:edit'],

      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #rightToolbar></template>
      <template #menuSlot="scope:any">
        <el-tooltip class="box-item" effect="dark" :content="t('crud.editText')" placement="top" v-if="scope.row.id !== constants.SUPER_ADMIN_ID">
          <div class="menu-btn">
            <el-button link type="primary" icon="Edit" @click="crudRef.handleUpdate(scope.row)" />
            <div class="el-divider el-divider--vertical" role="separator"></div>
          </div>
        </el-tooltip>
        <el-tooltip class="box-item" effect="dark" :content="t('crud.deleteText')" placement="top" v-if="scope.row.id !== constants.SUPER_ADMIN_ID">
          <div class="menu-btn">
            <el-popconfirm :title="t('crud.confirmDeleteTooltip')" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button link type="danger" icon="Delete" />
              </template>
            </el-popconfirm>
            <div class="el-divider el-divider--vertical" role="separator"></div>
          </div>
        </el-tooltip>
        <div class="menu-btn" v-if="scope.row.id !== constants.SUPER_ADMIN_ID">
          <el-tooltip content="重置密码" placement="top">
            <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']" />
          </el-tooltip>
        </div>
      </template>
      <template #priceId="scope:any">
        {{scope.row.price ? scope.row.price.name : '-'}}
      </template>

      <template #userType="scope:any">
        <DictTag :options="UserTypeEnum" :value="scope.row.userType" />
      </template>

      <template #status="scope:any">
        <el-switch
          v-if="scope.row.id !== constants.SUPER_ADMIN_ID"
          v-model="scope.row.status"
          active-value="Enabled"
          inactive-value="Disabled"
          @change="handleStatusChange(scope.row)"
        />
        <span v-else><DictTag :options="EnableStatusEnum" :value="scope.row.status" /></span>
      </template>
    </yt-crud>
    <ParkingListDialog ref="parkingListRef" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'

import {changeStatus, listUser, resetUserPwd, delUser, saveUser, deptTreeSelect} from '@/api/system/user'
import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'


import ParkingListDialog from '@/views/business/station/modules/ParkingList.vue'
import constants from '@/constants'
import {UserVO} from '@/api/system/user/types'
import {to} from 'await-to-js'
import {optionSelect as roleOptionSelect} from '@/api/system/role'
import { ElPopconfirm } from 'element-plus'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum, UserTypeEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum', 'user_type_enum'))
const { t } = useI18n()

const parkingListRef = ref()

const state = reactive({
  page: {
    pageSize: 12,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})


// 字典
const deptOptions = ref<any[]>([])
const roleOptions = ref<any[]>([])
const column = ref<IColumn[]>([
  {
    label: t('system.user.userType'),
    key: 'userType',
    type: 'select',
    componentProps: {
      options: UserTypeEnum,
    },
    search: false,
    formHide: true,
    slot: true,
  },
  {
    label: t('system.user.nickName'),
    key: 'nickName',
    hide: false,
    formHide: false,
    rules: [{ required: true, message: t('system.user.validator.nickName') }],
  },
  {
    label: t('system.user.userName'),
    key: 'userName',
    search: true,
    formHide: false,
    searchLabelWidth: 120,
    colSpan: 22,
    rules: [{ required: true, message: t('system.user.validator.userName') }],
  },
  {
    label: t('system.user.password'),
    key: 'password',
    hide: true,
    formHide: false,
    editHide: true,
    rules: [{ required: true, message: t('system.user.validator.password') }],
    componentProps: {
      type: 'password'
    },
  },
  {
    label: t('system.user.roleIds'),
    key: 'roleIds',
    colSpan: 22,
    type: 'select',
    componentProps: {
      multiple: true,
      keyAlias: 'id',
      valueAlias: 'id',
      labelAlias: 'roleName',
      options: roleOptions,
      placeholder: t('system.user.placeholder.roleIds')
    },
    rules: [{ required: true, message: t('system.user.validator.roleIds') }],
    hide: false,
    search: false,
    formHide: false,

  },
  {
    label: t('system.user.phone'),
    key: 'phone',
    hide: false,
    formHide: false,
  },
  {
    label: t('system.user.email'),
    key: 'email',
    hide: false,
    formHide: false,
  },
  {
    label: t('business.station.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: true,
    slot: true,
  },

  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  listUser({
    ...state.page,
    ...state.query,
  })
    .then((res: any) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}


const getDict = () => {
  roleOptionSelect().then((res)=>{
    roleOptions.value = res.data
  })

  deptTreeSelect().then((res)=>{
    deptOptions.value = res.data
  })

}
getDict()


// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  saveUser(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

// 弹窗前置操作
const openBeforeFun = ({ type}) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

const handleSuccess = () => {}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  delUser(row.id)
    .then(() => {
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    })
    .finally(() => {
      state.loading = false
    })
}

/** 重置密码按钮操作 */
const handleResetPwd = async (row: UserVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
    })
  )
  if (!err) {
    await resetUserPwd(row.id, res.value)
    proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value)
  }
}

const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>

<style lang="scss" scoped></style>
